import {
  setPx,
  getUrlParams
} from 'utils/util';
import config from './config';
import packages from 'core/packages';
export default (() => {
  return {
    props: {
      click: Function, //废弃，只有tabs组件用到
      dataFormatter: Function,
      titleFormatter: Function,
      labelFormatter: Function,
      clickFormatter: Function,
      formatter: Function,
      width: {
        type: [Number, String],
        default: 600
      },
      height: {
        type: [Number, String],
        default: 600
      },
      theme: {
        type: String
      },
      animation: {
        type: Boolean,
        default: true
      },
      child: {
        type: Object,
        default: () => {
          return {};
        }
      },
      time: {
        type: Number,
        default: 0
      },
      url: {
        type: String
      },
      disabled: {
        type: Boolean,
        default: true
      },
      dataType: {
        type: Number,
        default: 0
      },
      dataQuery: {
        type: Object,
        default: () => {
          return {};
        }
      },
      homeUrl: {
        type: String
      },
      dataAppend: {
        type: Boolean,
        default: false
      },
      dataMethod: {
        type: String,
        default: 'get'
      },
      id: {
        type: String,
        default: 'main_' + new Date().getTime()
      },
      data: {
        type: [Object, String, Array]
      },
      component: {
        type: Object,
        default: () => {
          return {};
        }
      },
      option: {
        type: Object,
        default: () => {
          return {};
        }
      },
      echartType: {
        type: String,
        default: ''
      },//echart类型，用于通用图，区分 哪种用
    },
    data() {
      return {
        propQuery: {},
        dataCount: 0,
        headerHeight: '',
        checkChart: '',
        myChart: '',
        dataChart: [],
        dataUrl: '',
        key: false,
        isChart: true
      };
    },
    watch: {
      clickFormatter(val) {
        console.log('--', val);

      },
      styleChartName() {
        this.$nextTick(() => {
          this.myChart && this.myChart.resize();
        });
      },
      url: {
        handler(val) {
          this.dataUrl = val || '';
        },
        deep: true,
        immediate: true
      },
      data: {
        handler() {
          this.updateData();
        },
        deep: true,
        immediate: true
      },
      width() {
        this.updateData();
      },
      height() {
        this.updateData();
      },
      theme: {
        deep: true,
        handler(val) {

          // 这三句一句都不能少
          this.myChart.dispose();
          this.init();
          this.updateData();
        }

      },
      option: {
        handler() {
          if (this.myChart && this.isChart) {
            // console.log('update', this.name);

            this.updateData();
          }
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      echartCommonOption() {
        return {
          textStyle: {
            fontFamily: 'FangSong',
          }
        }
      }, //echart配置公共属性
      dataChartLen() {
        return (this.dataChart || []).length;
      },
      switchTheme() {
        return this.vaildData(this.option.switchTheme, false);
      },
      name() {
        if (this.$el && this.$el.className) {
          const result = this.$el.className.replace(config.name, '');
          return result;
        } else {
          return config.name;
        }

      },
      minWidth() {
        const val = this.option.minWidth;
        if (val > this.width) return val;

      },
      isApi() {
        return this.dataType === 1;
      },
      style() {
        return this.component.style || {};
      },
      styleChartName() {
        const obj = {
          width: setPx(this.minWidth || this.width),
          height: setPx(this.height)
        };
        return obj;
      },
      styleSizeName() {
        return Object.assign({
          width: setPx((this.width)),
          height: setPx((this.height))
        }, (() => {
          if (this.minWidth) {
            return {
              overflowX: 'auto',
              overflowY: 'hidden'
            };
          }
          return {};
        })());
      }
    },
    mounted() {
      // console.log('--', {
      //   'a': 'a',
      //   ...this.echartCommonOption
      // });
      // console.log('aaa');

      this.init();
    },
    destroyed() {
      // console.log(this.myChart);

      // console.log('xiaohui');
      if (this.isChart) {
        window.echarts.dispose(this.myChart)

      }

    },
    methods: {
      finishEchartOption(option) {
        option.textStyle = {
          fontFamily: this.option.fontFamily,
        }
        if(option.title){
          option.title =  this.ishasprop(
            this.option.titleShow,
            {
              text: this.option.title,
              subtext: this.option.subtext || "",
              textStyle: {
                color: this.option.titleColor || "#333",
                fontSize: this.option.titleFontSize || 16,
              },
              left: this.option.titlePostion || "auto",
              subtextStyle: {
                color: this.option.subTitleColor || "#aaa",
                fontSize: this.option.subTitleFontSize || 14,
              },
            },
            {}
          )
        }
        if(option.grid){
          option.grid =  {
            left: this.option.gridX || 20,
            top: this.option.gridY || 60,
            right: this.option.gridX2 || 20,
            bottom: this.option.gridY2 || 60,
          }
        }
        if(option.tooltip && this.echartType!='newBarContrast'){
          option.tooltip =  this.ishasprop(
            this.formatter,
            {
              formatter: (name) => {
                return this.formatter(name, this.dataChart);
              },
            },
            {
              textStyle: {
                fontSize: this.option.tipFontSize,
                color: this.option.tipColor || "#fff",
              },
            }
          )
        }
        // &&this.component.prop!='newBarTwoY'&&  this.component.prop!='newPictorialbar' 
        if(option.xAxis  && this.component.prop!='newBarPercentage' && this.echartType!='' ){
          option.xAxis =  Object.assign( option.xAxis||{},{
            // type: "category" ,
            type: this.vaildData(this.option.category, true) ? "category" : "value",
            name: this.option.xAxisName,
            axisLine: {
              show: this.vaildData(this.option.xAxisLineShow, true),
              lineStyle: {
                color: this.option.lineColor || "#fff",
              },
            },
            // data: optionData.categories || [],
            inverse: this.vaildData(this.option.xAxisInverse, false),
            show: this.vaildData(this.option.xAxisShow, true),
            splitLine: {
              show: this.vaildData(this.option.xAxisSplitLineShow, false),
              lineStyle: {
                color: this.option.xAxisSplitLineColor,
              },
            },
            axisTick: {
              show: this.vaildData(this.option.xAxisTickShow, true),
              length: this.option.xAxisTickLength || 5,
              lineStyle: {
                color: this.option.xAxisTickColor,
              },
            },
            axisLabel: {
              show: this.vaildData(this.option.xAxisAxisLabelShow, true),
              interval: this.option.xAxisinterval || "auto",
              rotate: this.option.xAxisRotate || 0,
              fontFamily:this.option.xAxisFontFamily,
              fontWeight:this.option.xAxisFontWeight,
              textStyle: {
                color: this.option.xNameColor || "#fff",
                fontSize: this.option.xNameFontSize || 14,
              },
              formatter: (value) => {
                let strLen = value.length;
                let lastVal = value;
                if (strLen >= 0 && this.lineBreak > 0) {
                  if (strLen > this.lineBreak) {
                    lastVal =
                      lastVal.slice(0, this.lineBreak) +
                      "\n" +
                      lastVal.slice(this.lineBreak);
                  }
                }
  
                return lastVal;
              }
            }
          }
          );
        }
        if(option.yAxis   && this.echartType!='' ){
          option.yAxis =  Object.assign(option.yAxis||{},{
            // type:  "value",
            type: this.vaildData(this.option.category, true) ? "value" : "category",
            name: this.option.yAxisName,
            axisLabel: {
              show: this.vaildData(this.option.yAxisAxisLabelShow, true),
              fontFamily:this.option.yAxisFontFamily,
              fontWeight:this.option.yAxisFontWeight,
              textStyle: {
                color: this.option.yNameColor || "#fff",
                fontSize: this.option.yNameFontSize || 14,
              },
            },
            axisTick: {
              show: this.vaildData(this.option.yAxisTickShow, true),
              length: this.option.yAxisTickLength || 5,
              lineStyle: {
                color: this.option.yAxisTickColor,
              },
            },
            axisLine: {
              show: this.vaildData(this.option.yAxisLineShow, true),
              lineStyle: {
                color: this.option.lineColor || "#fff",
              },
            },
            inverse: this.vaildData(this.option.yAxisInverse, false),
            show: this.vaildData(this.option.yAxisShow, true),
            splitLine: {
              show: this.vaildData(this.option.yAxisSplitLineShow, true),
            },
          }
          );
       
        }
        // console.log(JSON.stringify(option));
        this.myChart.setOption(option, true);
      }, //echarts 最终赋值，引入 扩展符号失败。折中的方法
      init() {
        // 判断是否引入echart包
        if (!window.echarts) {
          packages.logs('echarts');
          return;
        }
        const main = this.$refs[this.id];
        if (main) {
          // 判断是否图表去初始化
          // console.log(config.echart);
          this.isChart = config.echart.includes(this.name);
          if (this.isChart) {

            this.myChart = window.echarts.init(main, this.theme);
          }
        }
      },
      updateUrl(url) {
        this.dataUrl = url;
        this.updateData();
      },
      // 更新数据核心方法
      updateData() {
        this.resetData && this.resetData();
        if (this.key) return;
        this.key = true;
        const callback = () => {
          this.key = false;
          // 动态数据
          if (this.isApi) {
            let dataUrl = this.dataUrl.replace(config.homeurl, this.homeUrl);
            const detail = (res) => {
              // 处理返回的数据
              const result = (() => {
                if (typeof this.dataFormatter === 'function') {
                  return this.dataFormatter(res.data);
                };
                return res.data || {};
              })();
              // 延迟效果数据逐步增加
              if (this.dataAppend) {
                result.forEach(ele => {
                  this.dataCount++;
                  setTimeout(() => {
                    this.dataChart.unshift(ele);
                  }, this.dataCount * 1500);
                });
              } else {
                this.dataChart = result;
              }
              if (this.isChart && this.myChart) {
                this.myChart.clear();
                this.updateChart();
                this.bindClick();
              }
            };
            let result = getUrlParams(dataUrl);
            let url = result.url;
            let params = Object.assign(result.params, this.dataQuery, this.propQuery);
            if (!window.axios) {
              packages.logs('axios');
              return;
            }
            this.$axios[this.dataMethod](url, (() => {
              if (this.dataMethod === 'get') {
                return {
                  params: params
                };
              } else if (this.dataMethod === 'post') {
                return params;
              }
            })()).then(res => {
              detail(res);
            });
          } else {
            // 静态数据
            if (typeof this.dataFormatter === 'function') {
              this.dataChart = this.dataFormatter(this.data);
            } else {
              this.dataChart = this.data;
            }
            if (this.isChart && this.myChart) {
              this.myChart.clear();
              this.updateChart();
              this.bindClick();
            }
          }
        };
        this.$nextTick(() => {
          callback();
          clearInterval(this.checkChart);
          if (this.time !== 0 && this.disabled) {
            this.checkChart = setInterval(() => {
              callback();
            }, this.time);
          }
        });
      },
      getLabelFormatter(name) {
        if (this.labelFormatter) {
          return this.labelFormatter(name, this.dataChart);
        }
        return name.value;
      },
      // 绑定点击事件
      bindClick() {
        /**
         * luliming
         * 先解除 click事件，防止组件启用刷新功能，不停绑定点击事件
         */
        this.myChart.off('click');
        /**
         * luliming
         * 1.多追加一个 id参数，用于解析选项卡 选的什么维度
         * 2.多追加一个 child参数，用于联动
         * @param {*} val 
         */
        this.myChart.on('click', e => {
          // console.log('clocks');
          // console.log(e);

          if (e.componentType === "geo") {
            // 点击区域 就不触发了，不好关联，不知道拿什么维度去关联
            if (this.clickFormatter) {
              // console.log(e);

              this.clickFormatter({
                type: this.name,
                name: e.name,
                value: e.name,
                data: this.dataChart,
                id: this.id,
                child: this.child
              });
            }
          } else if (e.marker) {
            if (this.clickFormatter) {
              if (this.name == 'map') {
                this.clickFormatter({
                  type: this.name,
                  name: e.value[2] || e.name,
                  value: e.value[2] || e.value,
                  data: this.dataChart,
                  id: this.id,
                  child: e.data.child
                });
              } else {
                this.clickFormatter({
                  type: this.name,
                  name: e.name,
                  value: e.value[2] || e.value,
                  data: this.dataChart,
                  id: this.id,
                  child: this.child
                });
              }

            }
          }
        });
      },
      // 下面俩都是chart的公共的方法,就放这里面共用
      getColor(index, first) {
        const barColor = this.option.barColor || [];
        if (barColor[index]) {
          const color1 = barColor[index].color1;
          const color2 = barColor[index].color2;
          const postion = (barColor[index].postion || 0.9) * 0.01;
          if (first) return color1;
          if (color2) {
            return {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: color1 // 0% 处的颜色
              }, {
                offset: postion,
                color: color2 // 100% 处的颜色
              }],
              global: false // 缺省为 false
            };
          }
          return color1;
        }
      },
      ishasprop(condition, isprop, alwaysObj) {
        return Object.assign((() => {
          return condition ? isprop : {};
        })(), alwaysObj);
      }
    }
  };
})();
